package com.stable.spider.eastmoney;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stable.utils.DateUtil;
import com.stable.utils.HttpUtil;
import com.stable.utils.TradeDateUtil;
import com.stable.vo.EastGzfx;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 估值分析
 */
@Component
@Log4j2
public class gzfxSpider {

    /**
     * 估值分析
     * http://data.eastmoney.com/gzfx/list.html
     * http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=GZFX_GGZB&token=894050c76af8597a853f5b408b759f5d&st=SECURITYCODE&sr=1&p=1&ps=50&uls={pages:(tp),data:(x),font:(font)}&filter=(MKT=%27cyb%27%20and%20TRADEDATE=^2020-07-27^)&rt=53198096
     *
     * https://www.sojson.com/encodeurl.html  字符转义
     *
     * type{中小板=zxb，创业板=cyb，深市主板=szzb，沪市主板=sh}
     * @return
     */
    public List<EastGzfx> getGZFX(int size, String datetime, String type) {
        String basicUrl = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=GZFX_GGZB&token=894050c76af8597a853f5b408b759f5d&st=SECURITYCODE&sr=1&p=1&ps="+ size +"&filter=(MKT=%27"+type+"%27%20and%20TRADEDATE=%5E"+datetime+"%5E)&rt=53198096";
        //String url = basicUrl.replace("(","%28").replace(")","%29");
        String result = HttpUtil.doGet2(basicUrl);

        List<EastGzfx> list = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(result);
        if (array.size() == 0) {
            return getGZFX(size,  DateUtil.convertDate(DateUtil.getDatetimeBeforNDayYYYYMMDD(DateUtil.convertDate2(datetime), 1)), type);
        }
        for (int i = 0; i < array.size(); i++) {
            EastGzfx ext = new EastGzfx();
            JSONObject jsonObject = array.getJSONObject(i);
            ext.setCode(jsonObject.getString("SECURITYCODE"));
            ext.setName(jsonObject.getString("SName"));
            ext.setHyname(jsonObject.getString("HYName"));
            ext.setTradeDate(jsonObject.getString("TRADEDATE"));
            ext.setNewPrice(jsonObject.getString("NEW"));
            ext.setPettm(jsonObject.getString("PE9"));
            ext.setPe(jsonObject.getString("PE7"));
            ext.setPb(jsonObject.getString("PB8"));
            ext.setPeg(jsonObject.getString("PEG1"));
            ext.setPs(jsonObject.getString("PS9"));
            ext.setPcf(jsonObject.getString("PCFJYXJL9"));

            list.add(ext);
        }
        return list;
    }


    public static void main(String[] args) {
        gzfxSpider hsgtcgSpider = new gzfxSpider();
        List<EastGzfx> shareSZ = hsgtcgSpider.getGZFX(2000, TradeDateUtil.getNearTradeDate(0), "cyb");
        int moreThanPettm70 = 0;
        for(EastGzfx da : shareSZ) {
            float v = Float.parseFloat(da.getPettm());
            if (v >= 70) {
                moreThanPettm70 ++;
            }
        }
        System.out.println(shareSZ.size()+"|"+moreThanPettm70);
    }


}
